# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo, donggu

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo
from coin2.support.product_info.futures_huobi_v1 import to_expire


def get_support_margin_mode(info):
  if 'support_margin_mode' in info:
    return info['support_margin_mode']
  else:
    return ""

def generate():
  mea = 'Futures.Huobi.v1-swap'
  me = 'Futures.Huobi'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get('https://api.hbdm.com/linear-swap-api/v1/swap_contract_info').json()['data']

  pis = []
  for info in data:
    # contract status:
    # 0: Delisting,
    # 1: Listing,
    # 2: Pending Listing,
    # 3: Suspension,
    # 4: Suspending of Listing,
    # 5: In Settlement,
    # 6: Delivering,
    # 7: Settlement Completed,
    # 8: Delivered
    if info['contract_status'] in [0]:
      continue
    native_symbol = info['contract_code']
    native_base = info['symbol']
    native_quote = 'USDT'
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = 'USDT'
    symbol = "%s-USDT.PERPETUAL" % base

    pi = dict(symbol=symbol,
              base=base,
              quote=quote,
              native_symbol=native_symbol,
              native_base=native_base,
              native_quote=native_quote,
              price_ticksize=float(info['price_tick']),
              qty_ticksize=float(1.0),
              contract_value=float(info['contract_size']),
              support_margin_mode=get_support_margin_mode(info))
    default_pi = default.product_info(me, symbol)
    default_pi['is_inverse'] = False
    pi = {**pi, **default_pi}
    pis.append(pi)

  data = requests.get(
      'https://api.hbdm.com/linear-swap-api/v1/swap_contract_info?business_type=futures'
  ).json()['data']
  for info in data:
    if info['contract_status'] in [0]:
      continue
    native_symbol = info['contract_code']
    native_base = info['symbol']
    native_quote = 'USDT'
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = 'USDT'
    symbol = "%s-USDT.%s" % (base, to_expire(info['contract_type']))

    pi = dict(
      symbol=symbol,
      base=base,
      quote=quote,
      native_symbol=native_symbol,
      native_base=native_base,
      native_quote=native_quote,
      price_ticksize=float(info['price_tick']),
      qty_ticksize=float(1.0),
      contract_value=float(info['contract_size']),
      support_margin_mode=get_support_margin_mode(info))
    default_pi = default.product_info(me, symbol)
    default_pi['is_inverse'] = False
    pi = {**pi, **default_pi}
    pis.append(pi)
  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
